﻿
using System.Collections.Generic;
using System;
using BCService.Utils;
using BCCommon;
using BCData.TMS.SpecificServiceType;
using BCDto.TMS.SpecificServiceType;
using BCEntity.TMS.SpecificServiceType;
using BCDto.Sim.Admin.Admin;
using BCData.TMS.SpecificServiceTypeOverWrite;
using BCEntity.TMS.SpecificServiceTypeOverWrite;
using BCData.TMS.Agent.AgentRecord;
using BCEntity.Common.EntityNameConst;
using BCService.Common.Area;

namespace BCService.TMS.SpecificServiceTypeOverWrite
{
    /// <summary>
    /// 特殊服务类型重写
    /// </summary>
    public class SpecificServiceTypeOverWriteService : ISpecificServiceTypeOverWriteService
    {
        private readonly IDatabaseContext databaseContext;
        private readonly ISpecificServiceTypeData specificServiceTypeData;
        private readonly ISpecificServiceTypeOverWriteData specificServiceTypeOverWriteData;
        private readonly IAgentRecordData agentRecordData;
        private readonly IRedisService redisService;
        private readonly IZoneService zoneService;
        private readonly string key = string.Format("{0}", EntityNameConst.SpecificServiceTypeEntity);
        private readonly string keyView = string.Format("{0}", EntityNameConst.SpecificServiceTypeViewEntity);


        #region 构造函数
        public SpecificServiceTypeOverWriteService(IZoneService zoneService, IRedisService redisService, ISpecificServiceTypeData specificServiceTypeData, ISpecificServiceTypeOverWriteData specificServiceTypeOverWriteData, IAgentRecordData agentRecordData, IDatabaseContext databaseContext)
        {
            this.zoneService = zoneService;
            this.redisService = redisService;
            this.agentRecordData = agentRecordData;
            this.specificServiceTypeOverWriteData = specificServiceTypeOverWriteData;
            this.specificServiceTypeData = specificServiceTypeData;
            this.databaseContext = databaseContext;
        }
        #endregion


        #region Add
        public SpecificServiceTypeOverWriteDto Add(SpecificServiceTypeOverWriteRequestDto specificServiceTypeOverWriteRequestDto, AdminDto admin)
        {
            if (admin.CompanyId == 1)
            {
                throw new ArgumentException("代理商专用接口!");
            }
            else
            {
                var agentRecord = this.agentRecordData.GetEntityByCompanyId(admin.CompanyId).Result;
                if (agentRecord == null)
                {
                    throw new ArgumentException("您不归属任何代理商，暂无权限添加");
                }

                if (string.IsNullOrWhiteSpace(specificServiceTypeOverWriteRequestDto.CountyCode))
                {
                    throw new ArgumentNullException("CountyCode");
                }
                var zoneEntity = this.zoneService.GetFromZoneEntity(specificServiceTypeOverWriteRequestDto.CountyCode);
                if (zoneEntity == null || zoneEntity.countyEntity == null)
                {
                    throw new ArgumentException("区县编码不存在!");
                }

                int count = specificServiceTypeOverWriteData.GetCountAsync(zoneEntity.provinceEntity.ProvinceCode, zoneEntity.cityEntity.CityCode, specificServiceTypeOverWriteRequestDto.CountyCode, agentRecord.AgentRecordId, specificServiceTypeOverWriteRequestDto.SpecificServiceTypeId).GetAwaiter().GetResult();
                if (count > 0)
                    throw new Exception("正在添加重复的记录!出现这种异常,请联系开发人员!");

                var org = specificServiceTypeData.GetEntityAsync(specificServiceTypeOverWriteRequestDto.SpecificServiceTypeId).GetAwaiter().GetResult() ?? throw new ArgumentException("指定的特殊服务类型不存在!");
                //添加

                return this.specificServiceTypeOverWriteData.InsertAsync(new SpecificServiceTypeOverWriteEntity()
                {
                    Enabled = specificServiceTypeOverWriteRequestDto.Enabled,
                    CreateAdminId = admin.AdminId,
                    CreateAdminName = admin.FullName,
                    CreateTime = DateTime.Now,
                    EditAdminId = admin.AdminId,
                    EditAdminName = admin.FullName,
                    UpdateTime = DateTime.Now,

                    AgentRecordId = agentRecord.AgentRecordId,
                    ProvinceCode = zoneEntity.provinceEntity.ProvinceCode,
                    CityCode = zoneEntity.cityEntity.CityCode,
                    CountyCode = specificServiceTypeOverWriteRequestDto.CountyCode,
                    SpecificServiceTypeId = specificServiceTypeOverWriteRequestDto.SpecificServiceTypeId,

                }).GetAwaiter().GetResult().As<SpecificServiceTypeOverWriteDto>();

            }
        }
        #endregion

        #region Update
        public SpecificServiceTypeViewDto Update(SpecificServiceTypeOverWritePutDto specificServiceTypeOverWritePutDto, AdminDto admin)
        {
            if (admin.CompanyId == 1)
            {
                throw new ArgumentException("代理商专用接口!");
            }
            else
            {
                var agentRecord = this.agentRecordData.GetEntityByCompanyId(admin.CompanyId).Result;
                if (agentRecord == null)
                {
                    throw new ArgumentException("您不归属任何代理商，暂无权限添加");
                }

                if (string.IsNullOrWhiteSpace(specificServiceTypeOverWritePutDto.CountyCode))
                {
                    throw new ArgumentNullException("CountyCode");
                }
                var zoneEntity = this.zoneService.GetFromZoneEntity(specificServiceTypeOverWritePutDto.CountyCode);
                if (zoneEntity == null || zoneEntity.countyEntity == null)
                {
                    throw new ArgumentException("区县编码不存在!");
                }

                //修改
                var orgEntity = specificServiceTypeOverWriteData.GetEntityAsync(specificServiceTypeOverWritePutDto.SpecificServiceTypeOverwriteId).GetAwaiter().GetResult() ?? throw new ArgumentException("找不到要修改的记录!");

                orgEntity.Enabled = specificServiceTypeOverWritePutDto.Enabled;
                orgEntity.EditAdminId = admin.AdminId;
                orgEntity.EditAdminName = admin.FullName;
                orgEntity.UpdateTime = DateTime.Now;

                this.redisService.DeleteMultipleKey(keyView, false);
                return specificServiceTypeOverWriteData.UpdateAsync(orgEntity).GetAwaiter().GetResult().As<SpecificServiceTypeViewDto>();

            }
        }
        #endregion

        #region 启用/禁用
        public SpecificServiceTypeOverWriteDto UpdateEnable(AdminDto admin, int overWriteId, bool enable)
        {
            if (admin.CompanyId == 1)
            {
                throw new ArgumentException("代理商专用接口!");
            }
            else
            {
                var agentRecord = this.agentRecordData.GetEntityByCompanyId(admin.CompanyId).Result;
                if (agentRecord == null)
                {
                    throw new ArgumentException("您不归属任何代理商，暂无权限操作!");
                }

                //修改
                var orgEntity = specificServiceTypeOverWriteData.GetEntityAsync(overWriteId).GetAwaiter().GetResult() ?? throw new ArgumentException("找不到要修改的记录!");

                orgEntity.Enabled = enable;
                orgEntity.EditAdminId = admin.AdminId;
                orgEntity.EditAdminName = admin.FullName;
                orgEntity.UpdateTime = DateTime.Now;

                this.redisService.DeleteMultipleKey(keyView, false);
                return specificServiceTypeOverWriteData.UpdateAsync(orgEntity).GetAwaiter().GetResult().As<SpecificServiceTypeOverWriteDto>();

            }
        }
        #endregion

        #region GetList  获取特殊服务类型记录--[分页]
        public PageableList<SpecificServiceTypeViewDto> GetList(AdminDto admin, string ProvinceCode, string CityCode, string CountyCode, int pageIndex, int pageSize)
        {
            if (admin.CompanyId == 1)
            {
                throw new ArgumentException("代理商专用接口!");
            }

            var agentRecord = this.agentRecordData.GetEntityByCompanyId(admin.CompanyId).Result;
            if (agentRecord == null)
            {
                throw new ArgumentException("您不归属任何代理商，暂无权限添加");
            }

            string cacheKey = this.redisService.GetKey(keyView, ProvinceCode, CityCode, CountyCode, agentRecord.AgentRecordId, pageIndex, pageSize);
            var result = redisService.TryGet(cacheKey, () =>
            {

                int fCount = 0;
                IEnumerable<SpecificServiceTypeViewEntity> fListView;
                (fListView, fCount) = specificServiceTypeOverWriteData.GetListAsync(ProvinceCode, CityCode, CountyCode, agentRecord.AgentRecordId, pageIndex, pageSize).GetAwaiter().GetResult();

                return new PageableList<SpecificServiceTypeViewDto>()
                {
                    Count = fCount,
                    Items = fListView.As<IEnumerable<SpecificServiceTypeViewDto>>(),
                    PageIndex = pageIndex,
                    PageSize = pageSize,
                    ServerTime = DateTime.Now,
                };
            }, TimeSpan.FromMinutes(30));
            return result;

        }
        #endregion

        #region GetList  获取总部特殊服务类型记录--[分页]
        public PageableList<SpecificServiceTypeDto> GetListBase(bool? isEnabled,int pageIndex, int pageSize)
        {
            int fCount = 0;
            IEnumerable<SpecificServiceTypeEntity> fList;
            string cacheKey = this.redisService.GetKey(key,isEnabled, pageIndex, pageSize);
            var result = this.redisService.TryGet(cacheKey, () =>
            {
                (fList, fCount) = specificServiceTypeData.GetListAsync(isEnabled, pageIndex, pageSize).GetAwaiter().GetResult();

                return new PageableList<SpecificServiceTypeDto>()
                {
                    Count = fCount,
                    Items = fList.As<IEnumerable<SpecificServiceTypeDto>>(),
                    PageIndex = pageIndex,
                    PageSize = pageSize,
                    ServerTime = DateTime.Now,
                };
            }, TimeSpan.FromMinutes(30));
            return result;
        }
        #endregion
    }
}